package com.panku.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
/**
 * 用于解析xml的工具类
 * @author jack
 *
 */
public class XmlUtil {
	
	/**
	 * 解析xml文件，转换为map集合
	 * @param path xml文件路径
	 * @return map集合
	 */
	public static Map<String, XMLBean> readXML(String filePath){
		Map<String, XMLBean> resultMap=new HashMap<>();
		SAXBuilder saxBuilder=new SAXBuilder();
		try {
			Document document=saxBuilder.build(new File(filePath));
			Element root =document.getRootElement();
			List<Element> childs=root.getChildren();
			//存放当前请求的路径，也就是map的key值
			String path="";
			for (Element e : childs) {		
				XMLBean xb=new XMLBean();
				path=e.getAttributeValue("path");
				String actionClass=e.getAttributeValue("actionClass");
				String method=e.getAttributeValue("method");
				List<Element> forwardList=e.getChildren();
				for (Element fe : forwardList) {
					String fname=fe.getAttributeValue("name");
					String fvalue=fe.getAttributeValue("value");
					xb.getForward().put(fname, fvalue);
				}				
				xb.setActionClass(actionClass);
				xb.setMethod(method);
				xb.setPath(path);
				resultMap.put(path, xb);
			}
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return resultMap;
	}
}
